const router = require('koa-router')()
const DB = require('../other/DB')
const token = require('../other/token');

router.prefix('/api/user')

router.post('/login', async function (ctx) {
  var paras = [ctx.request.body.username, ctx.request.body.password];
  var Users = await DB.query(`SELECT * FROM \`user\` WHERE username = ? AND password = ? AND desable = 0`, paras);
  if (Users.length == 0) throw new Error('用户名密码错误');
  Users[0].token = token.Jwt.generateToken({
    userInfo: {
      userName: ctx.request.body.username,
      permission: Users[0].permission
    }
  });
  delete Users[0].password;
  delete Users[0].create_time;
  delete Users[0].update_time;
  delete Users[0].desable;
  ctx.body = Users[0];
});

router.put('/regist', async function (ctx) {
  var paras = {
    username: ctx.request.body.username,
    password: ctx.request.body.password,
    nickname: ctx.request.body.nickname,
    permission: ctx.request.body.permission,
    desable: 0
  };
  if (!paras.username) throw new Error('用户名不能为空');
  if (!paras.password) throw new Error('密码不能为空');
  if (!paras.nickname) throw new Error('昵称不能为空');
  if (!['admin', 'user', 'watcher'].includes(paras.permission)) throw new Error('权限类型错误');
  var Users = await DB.query(`SELECT * FROM \`user\` WHERE username = ?`, [ctx.request.body.username]);
  if (Users.length > 0) {
    throw new Error('用户名已经被占用');
  } else {
    await DB.query(`INSERT INTO \`user\` SET ?`, paras);
    ctx.body = {
      message: '创建成功'
    };
  }
});

router.get('/', async function (ctx) {
  var users = await DB.query(`SELECT * FROM \`user\` WHERE desable = 0`);
  users.forEach(element => {
    delete element.password;
  });
  ctx.body = users;
});


router.post('/repassword', async function (ctx) {
  var paras = [ctx.userInfo.userName, ctx.request.body.OldPassword];
  var Users = await DB.query(`SELECT * FROM \`user\` WHERE username = ? AND password = ? AND desable = 0`, paras);
  if (Users.length == 1) {
    var paras = [ctx.request.body.password, ctx.userInfo.userName];
    await DB.query(`UPDATE \`user\` SET password = ? WHERE username = ?`, paras);
    ctx.body = {
      message: '修改成功'
    };
  } else if (Users.length == 0) {
    throw new Error('原密码错误，请重试');
  } else {
    throw new Error('未知错误，请联系管理员');
  };
})


module.exports = router